package com.wing.file.controller.admin;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.wing.common.utils.JsonResult;
import com.wing.file.factory.FileFactory;
import com.wing.file.model.response.FileVO;
import com.wing.file.service.AbstractService;
import com.wing.file.service.MinIOFileStorageService;
import com.wing.file.service.impl.PicService;
import com.wing.file.service.impl.TengXunFileServiceImpl;

import com.wing.web.annotation.AuthPass;

import com.wing.web.utils.LocaleMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 新文件存储服务
 */
@Api(value = "文件管理(新)", tags = "文件管理(新)")
@AuthPass
@CrossOrigin
@RestController
@Log4j2
@RequestMapping("file/admin/newFile")
public class NewFileController {

    @Autowired
    private FileFactory fileFactory;
    @Autowired
    private LocaleMessage localeMessage;

    @Value("${file.fileType}")
    private String fileType;

    @Autowired
    private PicService picService;

    @Autowired
    private MinIOFileStorageService minIOFileStorageServiceImpl;

    private  static  final  String PATH = "gallery/";
    private  static  final  String IMAGES_KU = "/images_ku/";

    @Autowired
    private TengXunFileServiceImpl tengXunFileServiceImpl;


    /**
     *
     * @param file
     * @param path 存储路劲 abc/ddd/, 可为空，如果为空默认放在跟目录
     * @return
     */
    @ApiOperation(value = "上传文件new")
    @ResponseBody
    @PostMapping("/uploadFile")
    public JsonResult uploadFile(@ApiParam(name = "attach",value = "attach", required = true) MultipartFile file,
                                 String path)  {
        try{
            if ("MINIO".equals(fileType)) {
                AbstractService factory = fileFactory.getFileService(fileType);
                FileVO fileVO = factory.uploadFile(file, path);
                return JsonResult.success("上传成功", fileVO);
            }else if ("TENGXUN".equals(fileType)) {
                AbstractService factory = fileFactory.getFileService(fileType);
                FileVO fileVO = factory.uploadFile(file, path);
                return JsonResult.success("上传成功", fileVO);
            }
            return JsonResult.exception("上传失败!未配置类型");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.exception("上传失败"+e.getMessage());
        }
    }

    /**
     * 下载文件
     *
     * @param
     * @return
     */
    @GetMapping("/downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String url = request.getParameter("url");
        String fileName = request.getParameter("filename");
        FileSystemView fsv = FileSystemView.getFileSystemView();
        File com = fsv.getHomeDirectory();
        System.out.println(com.getPath());
        //读取文件
        InputStream txtIn = new URL(url).openStream();
        OutputStream os = response.getOutputStream();
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);//下载的文件名称
        //文件缓存区
        byte[] bytes = new byte[1024];
        //判断输入流中的数据是否已经读完的标致
        int len = 0;
        while ((len = txtIn.read(bytes)) > 0) {
            os.write(bytes, 0, len);
        }
        if (os!=null){
            os.close();
        }
        if (txtIn!=null){
            txtIn.close();
        }
    }

    @ApiOperation(value = "minio下载文件")
    @GetMapping("/downLoad")
    public void fileupload(@RequestParam("fileUrl") String fileUrl,HttpServletResponse response){
        try{
            if ("MINIO".equals(fileType)) {
                AbstractService factory = fileFactory.getFileService(fileType);
                factory.downloadFile(fileUrl,response);
            }else if ("TENGXUN".equals(fileType)) {
                AbstractService factory = fileFactory.getFileService(fileType);
                factory.downloadFile(fileUrl,response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @ApiOperation(value = "获取某个文件夹下的所有文件信息")
    @PostMapping("/getFileVoListByDir")
    public List<FileVO> getFileVoListByDir(@RequestParam("dir") String dir) throws Exception {
        List<FileVO> fileVOS = null;
        fileVOS = tengXunFileServiceImpl.listObjects(dir);
        System.out.println(fileVOS);
        return fileVOS;
    }


    /**
     * 同步图库文件
     */
    @ApiOperation(value = "获取图库文件")
    @PostMapping("/syncDrawPic")
    public JsonResult syncDrawPic(@RequestParam(value = "companyInfoId",required = false) String companyInfoId) {
        List<FileVO> fileVOS = null;
        try {
            //获取原始的文件名
            if ("MINIO".equals(fileType)) {
                AbstractService factory = fileFactory.getFileService(fileType);
                fileVOS =  factory.listObjects(PATH);

            }
            else if ("TENGXUN".equals(fileType)) {
                String path = companyInfoId+IMAGES_KU;
                AbstractService factory = fileFactory.getFileService(fileType);
                fileVOS = factory.listObjects(path);
            }
            if (CollectionUtils.isNotEmpty(fileVOS)) {
               boolean isOk = picService.addInfo(fileVOS);
               if (isOk) {
                   return JsonResult.success("同步成功！");
               }
            }

        } catch (Exception e) {
            log.error("同步异常！异常信息:", e);
            return JsonResult.fail("同步失败！",e.getMessage());
        }
        return JsonResult.fail("同步失败！");
    }

}
